package com.queclink.ycm.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.queclink.ycm.entity.Report;
import com.queclink.ycm.tcp.GatewayTcpServer;
import com.queclink.ycm.thread.TcpThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;

/**
 * @author jim.li
 * @email jim.li@queclink.com
 * @date 2022-01-09 10:55:00
 */
@RestController
@RequestMapping()
public class TcpController {

    public static volatile HashMap<Integer, Boolean> isStopMap = new HashMap<>();

    // 用于测试
    @PostMapping("/tcp")
    public String newTcp(@RequestParam("port")Integer port) {
//        new Thread("tcp-Thread") {
//            @Override
//            public void run() {
//                super.run();
//                new GatewayTcpServer(port).startup();
//            }
//        }.start();
        if (!isLoclePortUsing(port)) {
            isStopMap.put(port, false);
            new TcpThread(port).run();
        } else {
            System.out.println(port + "该端口已被占用");
        }
        return "ok";
    }


    // 用于测试
    @PostMapping("/stop/tcp")
    public String stopTcp(@RequestParam("port")Integer port) {
//        new Thread("tcp-Thread") {
//            @Override
//            public void run() {
//                super.run();
//                new GatewayTcpServer(port).startup();
//            }
//        }.start();
//        isStopMap.put(port, true);

        GatewayTcpServer.closeServer(port);
        return "ok";
    }


    public boolean isLoclePortUsing(int port) {
        boolean flag = true;
        try {
            flag = isPortUsing("127.0.0.1", port);
        } catch (Exception e) {
        }
        return flag;
    }


    public boolean isPortUsing(String host, int port) throws UnknownHostException {
        boolean flkag = false;
        InetAddress theAddress = InetAddress.getByName(host);
        try {
            Socket socket = new Socket(theAddress, port);
            flkag = true;
        } catch (IOException e) {
        }
        return flkag;
    }
}
